var express = require('express');
var oss_client = require('../../../private/oss')
var router = express.Router();
var imageinfo = require('imageinfo')
var UUID = require('uuid')


async function putBuffer(remote_filename, buffer){
    var result = await oss_client.useBucket('xib-user-portrait').put(remote_filename, buffer)
    return result
}

router.use(async function(req, res, next){
    // 通过imageinfo获取图片的真实拓展名
    var imageInfo = imageinfo(req.file.buffer)
    // 通过uuid随机生成UUID作为文件标识名
    var filename_id = UUID.v4()
    // 构成完整的文件名
    var filename_full = `${filename_id}.${imageInfo.format}`
    try{
        response = await putBuffer(filename_full, req.file.buffer)
    }catch(err){
        // 上传失败, 返回错误信息
        res.json({
            success: false,
            errorInfo: 'UPLOAD_FILE_ERROR',
            errorSource: 'submit/file/userPortrait.js',
            errorVerbose: err
        })
    }
    // 上传成功, 返回文件标识名, 高宽比
    res.json({
        success: true,
        data:{
            filename_full: filename_full
        }
    }) 
})


module.exports = router;